package com.wosai.teach.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.agnetty.constant.HttpCst;
import com.android.agnetty.core.AgnettyFutureListener;
import com.android.agnetty.core.AgnettyResult;
import com.android.agnetty.future.http.HttpFuture;
import com.wosai.teach.R;
import com.wosai.teach.dao.UserDao;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.fragment.MySelfFragment;
import com.wosai.teach.handler.LoginHandler;
import com.wosai.teach.pojo.LogLogin;
import com.wosai.teach.pojo.User;
import com.wosai.teach.utils.AppCst;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.ImageLoaders;
import com.wosai.teach.utils.SharedSession;

/**
 * @author qiumy@wosaitech.com 2015-3-28 上午11:22:19
 * 
 *         登录界面
 * 
 */
public class LoginActivity extends Activity implements OnClickListener {

	protected static String String_autologin = null;
	private ImageView userHead;
	private TextView userNick;

	private Button button_log;
	private TextView text_reg;
	private EditText editText_workCode;
	private EditText editText_password;
	private LogLogin logLogin;
	private NewProgressDialog progressdialog;
	private static CheckBox autologin;
//	private static SharedPreferences sp;
	public static SharedPreferences sp;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);
			
		userHead = (ImageView) findViewById(R.id.login_head_image);
		userNick = (TextView) findViewById(R.id.login_nick_name);

		button_log = (Button) findViewById(R.id.login_button_login);
		text_reg = (TextView) findViewById(R.id.login_txt_register);
		editText_workCode = (EditText) findViewById(R.id.login_et_workcode);
		editText_password = (EditText) findViewById(R.id.login_et_password);

		String d_loginName = SharedSession.get(this, "d_loginName");
		String d_password = SharedSession.get(this, "d_password");
		editText_workCode.setText(d_loginName);
		editText_password.setText(d_password);

		text_reg.setOnClickListener(this);
		button_log.setOnClickListener(this);
		editText_password
				.setOnEditorActionListener(new EditText.OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView view, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE
								&& button_log.isEnabled()) {
							doLogin();
						}
						return false;
					}

				});

		UserDao userDao = new UserDao();
		AppGlobal.lastUser = userDao.getUserByLoginName(d_loginName);
		if (AppGlobal.lastUser != null) {
			ImageLoaders.getInstance().displayRoundImage(userHead,
					AppGlobal.lastUser.getIcon1(),
					R.drawable.login_default_head);
			if (AppGlobal.lastUser.getNickName() != null) {
				userNick.setText(AppGlobal.lastUser.getNickName());
			}

		}	
		
		initLogin();
	}

	private void initLogin() {
		logLogin = new LogLogin();
		logLogin.init(this);
	}

	@Override
	public void onResume() {
		super.onResume(); 
		autologin = (CheckBox) findViewById(R.id.login_checkbox_autologin);
		sp = getSharedPreferences("userInfo", 0);
        boolean choseAutoLogin =sp.getBoolean("autologin", false);
		//如果上次登录选了自动登录，那进入登录页面也自动勾选自动登录
        if(choseAutoLogin&&MySelfFragment.getnoautologin()!=1){
            autologin.setChecked(true);
            doLogin();
        }else{
        	SharedPreferences.Editor editor =sp.edit();
        	editor.putBoolean("autologin", false);
			editor.commit();
			MySelfFragment.setautologin(1);
        }
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		// 登录
		case R.id.login_button_login:
		{
			doLogin();
			break;
		}
		default:
			break;
		}
	}

	private void doLogin() {
		String workCode = editText_workCode.getText().toString();
		String password = editText_password.getText().toString();
		User user = new User();
		user.setLoginName(workCode);
		user.setPassword(password);

		if (TextUtils.isEmpty(workCode.trim())) {
			Toast.makeText(getApplicationContext(), "请输入登录名", Toast.LENGTH_LONG)
					.show();
			donotautologin();
			MySelfFragment.setautologin(1);
		} else if (TextUtils.isEmpty(password.trim())) {
			Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_LONG)
					.show();
			donotautologin();
			MySelfFragment.setautologin(1);
		} else {
			progressdialog = NewProgressDialog.showProgress(this, "登陆中...",
					false);
			button_log.setEnabled(false);
			SharedSession.save(this, "d_loginName", workCode);
			SharedSession.save(this, "d_password", password);
			// /appLogin/{loginName}/{password}/{imei}/{imsi}/{appVer}/{osType}/{osVer}/{manufacture}/{phoneModel}/{rom}/{ram}/{sd}/{freeRom}/{freeRam}/{freeSd}/{screenX}/{screenY}/{network}
			String url = AppCst.HTTP_URL_LOGIN;
			url = url.replace("{loginName}", workCode + "")
					.replace("{password}", password + "")
					.replace("{imei}", logLogin.getImei() + "")
					.replace("{imsi}", logLogin.getImsi() + "")
					.replace("{appVer}", logLogin.getAppVer() + "")
					.replace("{osType}", logLogin.getOsType() + "")
					.replace("{osVer}", logLogin.getOsVer() + "")
					.replace("{manufacture}", logLogin.getManufacture() + "")
					.replace("{phoneModel}", logLogin.getPhoneModel() + "")
					.replace("{rom}", logLogin.getRom() + "")
					.replace("{ram}", logLogin.getRam() + "")
					.replace("{sd}", logLogin.getSd() + "")
					.replace("{freeRom}", logLogin.getFreeRom() + "")
					.replace("{freeRam}", logLogin.getFreeRam() + "")
					.replace("{freeSd}", logLogin.getFreeSd() + "")
					.replace("{screenX}", logLogin.getScreenX() + "")
					.replace("{screenY}", logLogin.getScreenY() + "")
					.replace("{network}", logLogin.getNetwork() + "");
			System.out.println(url);
			new HttpFuture.Builder(this, HttpCst.GET).setUrl(url)
					.setHandler(LoginHandler.class)
					.setListener(new AgnettyFutureListener() {
						@Override
						public void onComplete(AgnettyResult result) {
							super.onComplete(result);
							Object rst = result.getAttach();
							if (rst != null && (Boolean) rst) {
								Toast.makeText(LoginActivity.this, "登录成功",
										Toast.LENGTH_LONG).show();
								if(autologin.isChecked()){
									SharedPreferences.Editor editor =sp.edit();
									editor.putBoolean("autologin", true);
									editor.commit();
									MySelfFragment.setautologin(0);
									}else{
										MySelfFragment.setautologin(1);
										donotautologin();
									}
								AppGlobal.hasSchoolMate = false;
								Intent it = new Intent(LoginActivity.this,
										MainActivity.class);
								it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(it);
//								new Thread(new Runnable(){   
//								    public void run(){   
//								        try {
//											Thread.sleep(100);
//										} catch (InterruptedException e) {
//											// TODO Auto-generated catch block
//											e.printStackTrace();
//										}   
//								        finish();
//								    }   
//								}).start();
								finish();
							} else {
								Toast.makeText(LoginActivity.this, "用户名或密码错误",
										Toast.LENGTH_LONG).show();
								donotautologin();
								MySelfFragment.setautologin(1);
					            autologin.setChecked(false);
							}
							button_log.setEnabled(true);
							if (progressdialog != null) {
								progressdialog.dismiss();
							}
						}

						@Override
						public void onException(AgnettyResult result) {
							super.onException(result);
							result.getException().printStackTrace();
							Toast.makeText(LoginActivity.this, "登录失败",
									Toast.LENGTH_LONG).show();
							button_log.setEnabled(true);
							if (progressdialog != null) {
								progressdialog.dismiss();
							}
						}
					}).execute();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if(autologin.isChecked()){
				SharedPreferences.Editor editor =sp.edit();
				editor.putBoolean("autologin", true);
				editor.commit();
				MySelfFragment.setautologin(0);
				}else{
					MySelfFragment.setautologin(1);
					donotautologin();
				}
			AppUtil.AppOut(keyCode, event, this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	public static void donotautologin(){
		SharedPreferences.Editor editor =sp.edit();
		editor.putBoolean("autologin", false);
		editor.commit();
		autologin.setChecked(false);
	}
	
}
